﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ibtnReg_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid&&checkVcode())
        {
            BLL.Users blluser = new BLL.Users();
            MODEL.Users model=new MODEL.Users();
            model.UName = txtName.Text.Trim();
            model.Pwd =common.GetMD5(txtPwd.Text.Trim());
            model.Question = ddlQuestion.SelectedItem.ToString().Trim();
            model.Answer = txtAnswer.Value.Trim();
            model.Email = txtEmail.Text.Trim();
            model.QQ = txtQQ.Text.Trim();
            model.Phone = txtPhone.Text.Trim();
            //在其中的一层try,catch就行，如果有异常，它会一层接一层的抛出来
            try
            {
                if (blluser.Add(model))
                {
                    MODEL.Users currentuser = new MODEL.Users();
                    currentuser = blluser.getModel(model.UName);
                    //将当前用户对象保存到session中
                    Session["currentUser"] = currentuser;
                    MessageBox.Show(this, "注册成功");
                    //跳回首页
                    //Server.Transfer("index.aspx");
                    MessageBox.script(this, "window.location='index.aspx';");
                }
                else
                {
                    MessageBox.Show(this, "用户名已存在");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,ex.Message+"注册失败");
            }
            //Response.End();不能在此写这一句，否则前台页面的代码无法执行，造成错误
        }
    }

    #region 检查验证码是否正确
    /// <summary>
    /// 检查验证码是否正确
    /// </summary>
    /// <returns></returns>
    private bool checkVcode()
    {
        if (Session["vCode"] != null)
        {
            if (txtVCode.Text.Trim() == Session["vCode"].ToString())
            {
                return true;
            }
            else
            {
                MessageBox.Show(this, "验证码错误");
                return false;
            }
        }
        else
        {
            MessageBox.Show(this, "验证码过期了");
            return false;
        }
    } 
    #endregion
}